package com.ifp.opengate.boot.task;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.ifp.opengate.boot.constants.Constants;
import com.ifp.opengate.boot.emum.ErrorEnum;
import com.ifp.opengate.boot.utils.RedisUtils;

/**
 * @Classname ApiDeployTask
 * @Description api发布
 * @Date 2019/7/23 17:28
 * @Created by zzh
 *          <p>
 *          zhuzh@belink.com
 *          </p>
 * @Version 1.0
 */
@Component
public class ApiDeployTask implements ApplicationRunner {

    @Autowired
    RedisUtils redisUtils;

    /**
     * 访问参数初始化
     */
    private Map<String, Map<Object, Object>> apiInfoMap = new HashMap<String, Map<Object, Object>>();

    public Map<String, Map<Object, Object>> getApiInfoMap() {
        return apiInfoMap;
    }

    public void setApiInfoMap(Map<String, Map<Object, Object>> apiInfoMap) {
        this.apiInfoMap = apiInfoMap;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Map<Object, Object> apiInfoMaps = redisUtils.hmget(Constants.OPENGATE_GROUP_API);
        for (Map.Entry<Object, Object> apikey : apiInfoMaps.entrySet()) {
            addApiInfo((String)apikey.getKey());
        }
    }

    public String addApiInfo(String apiKey) {
        Map<Object, Object> apiInfoMap = redisUtils.hmget(apiKey);
        String apiId = (String)apiInfoMap.get(Constants.API_ID);
        String apiVersion = (String)apiInfoMap.get(Constants.API_VERSION);
        String apiName = (String)apiInfoMap.get(Constants.API_NAME);
        String protocolKey = Constants.OPENGATE_API_PROTOCOL_REL + apiId + "_" + apiVersion;
        Map<Object, Object> apiPotocolrel = redisUtils.hmget(protocolKey);
        for (Map.Entry<Object, Object> potocolRel : apiPotocolrel.entrySet()) {
            Map<Object, Object> potocolMap = redisUtils
                .hmget(Constants.OPENGATE_API_PROTOCOL_ + potocolRel.getValue() + Constants.BOTTOM_LINE + apiVersion);
            apiInfoMap.put(potocolRel.getKey(), potocolMap);
        }
        this.apiInfoMap.put(apiKey, apiInfoMap);
        // Trace.logInfo(Trace.MODULE_COMMON, "apiInfoMap:[{}]", apiInfoMap);

        // if (Cat.isInitialized()) {
        // Transaction transaction = Cat.getProducer().newTransaction("Api.info", apiId + apiVersion + "[" + apiName +
        // "]");
        // transaction.setStatus("0");
        // transaction.complete();
        // }
        return ErrorEnum.success.code();
    }

    public void removeApiInfo(String apiKey) {
        apiInfoMap.remove(apiKey);
        // TODO:测试代码
        try {

            // Trace.logInfo(Trace.MODULE_COMMON, "是否包含{}。结果:{}", apiKey, apiInfoMap.containsKey(apiKey));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
